Ext.onReady(function() {

    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';
    var pagesize = 22;
    var gridisedit = false;
    var openUrl = basePath
            + 'JarpListener?className=cn.com.jsepc.rep.report.FillDataDAO';
    openUrl += '&methodName=getDataGrid&paramCount=5&param_2=' + repid + '&param_3=' + corpid + '&param_4=' + getDemlist();

    var modalwin_f = new Ext.Window({
        id: 'modalwin_f',
        title: "维度信息",
        border: false,
        bodyBorder: false,
        layout: 'fit',
        width: 435,
        height: 510,
        closeAction: 'hide',
        //	    plain: true,
        modal: true,
        tbar: ['-', {
                text: ' 确定 ',
                handler: function() {
                    selectItem();
                    modalwin_f.hide();
                }
            }, '-', {
                text: ' 关闭 ',
                handler: function() {
                    modalwin_f.hide();
                }
            }, '-'],
        items: [p_wdxx]
    });

    /**
     * 自动设定值
     * @type type
     */
    var setValue = new Ext.FormPanel({
        id: 'setValue',
        labelWidth: 80,
        width: '98%',
        height: '100%',
        bodyStyle: 'padding: 4px',
        border: false,
        frame: true,
        autoScroll: true,
        items: [{
                title: '自动设定值',
                layout: 'form',
                xtype: 'fieldset',
                collapsible: true,
                collapsed: false,
                labelAlign: 'right',
                height: '100%',
                defaults: {
                    width: '100%'
                },
                items: [{
                        xtype: "textfield",
                        fieldLabel: "当期值",
                        emptyText: '自动设定该指标的当期值',
                        disabled: false,
                        id: 'bianhao_repval',
                        anchor: "70%"
                    }, {
                        xtype: "textfield",
                        fieldLabel: "累计值",
                        emptyText: '自动设定该指标的累计值',
                        disabled: false,
                        id: 'bianhao_sumval',
                        anchor: "70%"
                    }]
            }]
    });

    /**
     * 根据电网的最新需求，历史维度过滤页面停止使用，新的维度过滤页面与导出线下采集模板保持一致，现在模板的维度过滤页面废弃
     * author：赵远
     * 2013-06-07
     */
    var shuju_win = new Ext.Window({
        id: 'shuju_win',
        title: "筛选维度",
        border: false,
        bodyBorder: false,
        // layout:'fit',
        width: 435,
        height: 510,
        closeAction: 'hide',
        modal: true,
        tbar: ['-', {
                text: ' 确定 ',
                handler: function() {
                    //进行数据操作
                    selectItem();
                    shuju_win.hide();
                }
            }, '-', {
                text: ' 关闭 ',
                handler: function() {
                    shuju_win.hide();
                }
            }, '-'],
        items: [shuju_weidu, shuju_pal]
    });
    var store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: openUrl
        }),
        reader: jReader1
    });
    var sm = new Ext.grid.RowSelectionModel({
        singleSelect: true
    });
    cm.defaultSortable = true;
    var grid = new Ext.grid.EditorGridPanel({
        id: 'grid_t',
        // region : 'center',
        anchor: '100% 95%',
        // renderTo:'qrgridDiv',
        store: store,
        //sm:sm,  
        cm: cm,
        viewConfig: {
            forceFit: false
        },
        frame: true,
        //  loadMask:true,//数据加载时的遮罩功能 
        stripeRows: true, //显示行的分隔符
        columnLines: true,
        clicksToEdit: 1,
        autoScroll: true, //控制滚动条
        height: screen.height - 400,
        stateful: true,
        stateId: 'grid_t',
        bbar: new Ext.PagingToolbar({
            pageSize: pagesize,
            store: store,
            paramNames: {
                start: 'param_0',
                limit: 'param_1'
            },
            displayInfo: true,
            emptyMsg: '没有数据需要显示&nbsp;&nbsp;'
        })
    });

    /* store.load({params : {
     param_0:0,
     param_1:pagesize
     }});
     */

    store.on("beforeload", function() {
        if (gridisedit) {
            saveForm();
        }
    });
    function getDemlist() {
        var sender = {};
        var array = [];
        for (var i = 0; i < dimLen; i++) {
            var o = {};
            o.facdimtable = Ext.ComponentMgr.get("facdimtable" + i).getValue();
            o.facdimcodecol = Ext.ComponentMgr.get("facdimcodecol" + i).getValue();
            o.facdimvalue = Ext.ComponentMgr.get("facdimvalue" + i).getValue();
            //demArr[i]  = o;
            array.push(o);
        }
        sender.demlist = array;
        //  alert(Ext.util.JSON.encode(sender));
        return Ext.util.JSON.encode(sender);
    }

    /**
     * 获取导出数据采集模版筛选的维度
     */
    function getExportDemlist() {
        var sender = {};
        var array = [];
        for (var i = 0; i < dimLen; i++) {
            var o = {};
            o.facdimtablewan = Ext.ComponentMgr.get("facdimtablewan" + i).getValue();
            o.facdimcodecolwan = Ext.ComponentMgr.get("facdimcodecolwan" + i).getValue();
            o.facdimvaluewan = Ext.ComponentMgr.get("facdimvaluewan" + i).getValue();
            o.facdimfieldwan = Ext.ComponentMgr.get("facdimfieldwan" + i).getValue();
            o.facdimtable_weidu = Ext.ComponentMgr.get("facdimtable_weidu" + i).getValue();
            o.facdimcodecol_weidu = Ext.ComponentMgr.get("facdimcodecol_weidu" + i).getValue();
            o.facdimvalue_weidu = Ext.ComponentMgr.get("facdimvalue_weidu" + i).getValue();
            //demArr[i]  = o;
            array.push(o);
        }
        sender.demlist = array;
        // alert(Ext.util.JSON.encode(sender));
        return Ext.util.JSON.encode(sender);
    }
    //主视图
    var viewport = new Ext.Viewport({
        layout: 'border',
        items: [{
                tbar: ['-', {
                        text: '维度过滤',
                        iconCls: '',
                        handler: function() {
                            shuju_win.show();
                            shuju_win.doLayout();
                        }
                    }, '-', {
                        text: '保存',
                        handler: function() {
                            saveForm();
                        }
                    }, '-', {
                        text: '关闭',
                        handler: function() {
                            window.close();
                        }
                    }, '-', {
                        text: '参照上期模版',
                        handler: function() {
                            showSQ();
                        }
                    }, {
                        text: '包含值',
                        xtype: 'label'
                    }, {
                        xtype: 'checkbox',
                        id: 'bhz'
                    }, '-', {
                        text: '导出线下采集模版',
                        handler: function() {
                            selectItem_shuju();
                            getExportDemlist();
                        }
                    }, '-', {
                        text: '使用线下采集模板导入',
                        handler: function() {
                            win_upload.show();
                        }
                    }, {
                        text: '筛选完成值',
                        hidden: true,
                        xtype: 'label'
                    }, {
                        xtype: 'checkbox',
                        hidden: true,
                        id: 'zxwcz'
                    }
                ],
                region: 'center',
                deferredRender: false,
                frame: true,
                layout: 'border',
                items: [
                    {
                        region: 'center',
                        deferredRender: false,
                        frame: true,
                        layout: 'anchor',
                        items: [grid]
                    }
                ]
            }]

    });
    //回车换行
    grid.on("afteredit", function(e) {
        gridisedit = true;
        if (e.row < grid.getStore().getCount() - 1) {
            var delay = new Ext.util.DelayedTask(function() {
                grid.startEditing(e.row + 1, e.column);
            });
            delay.delay(50);

        }
    });

    var form = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        labelWidth: 70,
        labelHeight: 150,
        fileUpload: true,
        defaultType: 'textfield',
        items: [{
                xtype: 'textfield',
                fieldLabel: '选择文件',
                name: 'userfile',
                id: 'userfile',
                inputType: 'file',
                anchor: '95%' // anchor width by percentage  
            }]

    });
    //上传文件的窗口
    var win_upload = new Ext.Window({
        title: '上传文件',
        width: 450,
        height: 180,
        modal: true,
        x: 100,
        y: 50,
        layout: 'form',
        autoScroll: true,
        constrain: true,
        bodyStyle: 'padding:10px 10px 10px 10px;',
        items: form,
        buttons: [{
                text: '确认上传',
                handler: function() {
                    if (form.form.isValid()) {
                        if (Ext.getCmp('userfile').getValue() == '') {
                            Ext.Msg.alert('提示', '请选择要上传的文件');
                            return;
                        }
                        Ext.MessageBox.show({
                            title: '请稍后....',
                            msg: '文件正在上传中....',
                            progressText: '',
                            width: 300,
                            progress: true,
                            closable: false,
                            animEl: 'loding'
                        });
                        form.getForm().submit({
                            url: basePath + 'servlet/Upload',
                            method: 'POST',
                            success: function(form, action) {
                                Ext.Msg.alert('成功', '文件上传成功！');
                                win_upload.hide();
                                importXls(action.result.url);
                            },
                            failure: function(form, action) {
                                Ext.Msg.alert('错误', "文件上传失败，请重新操作！");
                            }
                        })
                    }
                }
            }, {
                text: '关闭',
                handler: function() {
                    win_upload.hide();
                }
            }],
        closable: false,
        draggable: false,
        resizable: false
    });

    function saveForm() {
        var objInfo = new Object();
        //检查是否编辑，并提示保存
        var store = grid.getStore();
        //得到修改过的Recored的集合  
        var bhz = czsqz;
        var modified = store.modified.slice(0);
        if (bhz) {
            modified=store.getRange(0,store.getTotalCount());
            var jsonArray = [];
        var breturn = false;
        Ext.each(modified, function(m) {
            //m.data中保存的是当前Recored的所有字段的值json，不包含结构信息 
            if (m && m.data) {
                var val = m.data.REPVAL;
                if (isDigitzh(val)) {
                    breturn = true;
                    alert("只能是数字或者+-符号！");
                    return;
                }
            }
            jsonArray.push(m.data);
        });
        if (breturn) {
            return;
        }
        objInfo.listData = jsonArray;
            Ext.MessageBox.alert("提示","系统会更新所有数据（所有页），请稍候")
            czsqz = false;
            var saveItemInfoUrl = "";
            saveItemInfoUrl = '?className=cn.com.jsepc.rep.report.FillDataSQ';
            saveItemInfoUrl += '&methodName=getGridData';
            saveItemInfoUrl += '&paramCount=2&param_0=' + repid + "&param_1=" + roleid;
            saveItemInfoUrl = basePath + 'JarpListener' + saveItemInfoUrl;
            httpR_itemInfo = getXMLHttpRequest();
            httpR_itemInfo.onreadystatechange = returnItemUpdate;
            httpR_itemInfo.open("POST", saveItemInfoUrl, true);
            httpR_itemInfo.send(Ext.util.JSON.encode(objInfo));
            return ;
        } else {
            modified = store.modified.slice(0);
        }
        if (modified == null || modified == "")
        {
            return;
        }

        gridisedit = false;
        //将数据放到另外一个数组中  
        var jsonArray = [];
        var breturn = false;
        Ext.each(modified, function(m) {
            //m.data中保存的是当前Recored的所有字段的值json，不包含结构信息 
            if (m && m.data) {
                var val = m.data.REPVAL;
                if (isDigitzh(val)) {
                    breturn = true;
                    alert("只能是数字或者+-符号！");
                    return;
                }
            }
            jsonArray.push(m.data);
        });
        if (breturn) {
            return;
        }
        objInfo.listData = jsonArray;
        var saveItemInfoUrl = "";
        saveItemInfoUrl = '?className=cn.com.jsepc.rep.report.FillDataDAO';
        saveItemInfoUrl += '&methodName=DatatbUpdate';
        saveItemInfoUrl += '&paramCount=2&param_0=' + repid + "&param_1=" + roleid;
        saveItemInfoUrl = basePath + 'JarpListener' + saveItemInfoUrl;
        httpR_itemInfo = getXMLHttpRequest();
        httpR_itemInfo.onreadystatechange = returnItemUpdate;
        httpR_itemInfo.open("POST", saveItemInfoUrl, true);
        httpR_itemInfo.send(Ext.util.JSON.encode(objInfo));

    }

    function returnItemUpdate() {
        if (httpR_itemInfo.readyState == 4) {
            if (httpR_itemInfo.status == 200) {
                ret = httpR_itemInfo.responseText;
                if (ret == 'ok') {
                    alert('数据修改成功！');
                    query();
                } else if (ret == 'no') {
                    alert('数据没有修改！');
                } else {
                    alert('数据修改失败！');
                }
            }
        }
    }



    //点击 参照上期模版 执行
    function showSQ() {
        var bhz = Ext.getCmp("bhz").getValue();
        var zxwcz = Ext.getCmp("zxwcz").getValue();  //筛选完成值

        if (zxwcz) {
            //判断是否有上期值
            var saveItemInfoUrl = "";
            saveItemInfoUrl = '?className=cn.com.jsepc.rep.report.FillDataSQ_Wan';
            saveItemInfoUrl += '&methodName=hasSQ';
            saveItemInfoUrl += '&paramCount=1&param_0=' + repid;
            saveItemInfoUrl = basePath + 'JarpListener' + saveItemInfoUrl;
            httpR_itemInfo = getXMLHttpRequest();
            httpR_itemInfo.onreadystatechange = hasvalue;
            httpR_itemInfo.open("POST", saveItemInfoUrl, true);
            httpR_itemInfo.send();
            function hasvalue() {
                if (httpR_itemInfo.readyState == 4) {
                    if (httpR_itemInfo.status == 200) {
                        ret = httpR_itemInfo.responseText;
                        if (ret == 'ok') {

                        } else {
                            Ext.MessageBox.alert("错误", "没有上期值模板，请去掉参照上期值后并手动筛选维度")
                        }
                    }
                }
            }
        } else {
            //判断是否有上期值
            var saveItemInfoUrl = "";
            saveItemInfoUrl = '?className=cn.com.jsepc.rep.report.FillDataSQ';
            saveItemInfoUrl += '&methodName=hasSQ';
            saveItemInfoUrl += '&paramCount=1&param_0=' + repid;
            saveItemInfoUrl = basePath + 'JarpListener' + saveItemInfoUrl;
            httpR_itemInfo = getXMLHttpRequest();
            httpR_itemInfo.onreadystatechange = hasvalue;
            httpR_itemInfo.open("POST", saveItemInfoUrl, true);
            httpR_itemInfo.send();
            function hasvalue() {
                if (httpR_itemInfo.readyState == 4) {
                    if (httpR_itemInfo.status == 200) {
                        ret = httpR_itemInfo.responseText;
                        if (ret == 'ok') {

                        } else {
                            Ext.MessageBox.alert("错误", "没有上期值模板，请去掉参照上期值后并手动筛选维度")
                        }
                    }
                }
            }


            //判断是否有当期值
            var requestHasThis = "";
            requestHasThis = '?className=cn.com.jsepc.rep.report.FillDataSQ';
            requestHasThis += '&methodName=hasThis';
            requestHasThis += '&paramCount=1&param_0=' + repid;
            requestHasThis = basePath + 'JarpListener' + requestHasThis;
            httpR_itemInfo = getXMLHttpRequest();
            httpR_itemInfo.onreadystatechange = hasThis;
            httpR_itemInfo.open("POST", requestHasThis, true);
            httpR_itemInfo.send();
            function hasThis() {
                if (httpR_itemInfo.readyState == 4) {
                    if (httpR_itemInfo.status == 200) {
                        ret = httpR_itemInfo.responseText;
                        if (ret == 'ok') {

                        } else {
                            Ext.MessageBox.alert("错误", "维度表数据缺失，请联系维护人员维护相关维度表")
                        }
                    }
                }
            }

        }

        if (!zxwcz) {
            if (bhz) {
                czsqz = true;
                var openUrl = basePath
                        + 'JarpListener?className=cn.com.jsepc.rep.report.FillDataSQ';
                openUrl += '&methodName=getGridData&paramCount=5&param_2=' + repid + '&param_3=' + corpid + '&param_4=true';
                hideColumn([]);
            } else {
                var openUrl = basePath
                        + 'JarpListener?className=cn.com.jsepc.rep.report.FillDataSQ';
                openUrl += '&methodName=getGridData&paramCount=5&param_2=' + repid + '&param_3=' + corpid + '&param_4=false';
                hideColumn([]);
            }
        } else {
            if (bhz) {
                var openUrl = basePath
                        + 'JarpListener?className=cn.com.jsepc.rep.report.FillDataSQ_Wan';
                openUrl += '&methodName=getDataGrid&paramCount=5&param_2=' + repid + '&param_3=' + corpid + '&param_4=true';
                hideColumn([]);
            } else {
                var openUrl = basePath
                        + 'JarpListener?className=cn.com.jsepc.rep.report.FillDataSQ_Wan';
                openUrl += '&methodName=getDataGrid&paramCount=5&param_2=' + repid + '&param_3=' + corpid + '&param_4=false';
                hideColumn([]);
            }
        }

        store.proxy = new Ext.data.HttpProxy({
            url: openUrl
        });
        store.load({
            params: {
                param_0: 0,
                param_1: pagesize
            }
        });

    }

    //查询
    function selectItem() {
        if (gridisedit) {
            saveForm();
        } else {
            var hideCol = [];
            var array = [];
            var sender = {};
            for (var i = 0; i < dimLen; i++) {
                var o = {};
                o.facdimtable = Ext.ComponentMgr.get("facdimtablewan" + i).getValue();
                o.facdimcodecol = Ext.ComponentMgr.get("facdimcodecolwan" + i).getValue();
                o.facdimvalue = Ext.ComponentMgr.get("facdimvaluewan" + i).getValue();
                o.facdimfield = Ext.ComponentMgr.get("facdimfieldwan" + i).getValue();
                if (o.facdimvalue == "") {
                    o.facdimvalue = "99999";
                    hideCol.push(o.facdimfield);
                }
                array.push(o);
            }
            sender.demlist = array;
            sender.iswcz = Ext.getCmp("iswcz").getValue();
            //没有筛选完成值的情况
            if (hideCol.length == dimLen) {
                var openUrl = basePath
                        + 'JarpListener?className=cn.com.jsepc.rep.report.FillDataDAO';
                openUrl += '&methodName=getDataGrid&paramCount=5&param_2=' + repid + '&param_3=' + corpid + '&param_4=' + getExportDemlist();
            } else {
                var openUrl = basePath
                        + 'JarpListener?className=cn.com.jsepc.rep.report.FillDataDAO';
                openUrl += '&methodName=getDataGridAll&paramCount=5&param_2=' + repid + '&param_3=' + corpid + '&param_4=' + getExportDemlist();
                hideColumn([]);
            }


            store.proxy = new Ext.data.HttpProxy({
                url: openUrl
            });
            store.load({
                params: {
                    param_0: 0,
                    param_1: pagesize
                }
            });
        }

    }

    /**
     * 导出数据采集模版
     */
    function selectItem_shuju() {
        var hideCol = [];
        var array = [];
        var sender = {};
        for (var i = 0; i < dimLen; i++) {
            var o = {};
            o.facdimtable = Ext.ComponentMgr.get("facdimtable_weidu" + i).getValue();
            o.facdimcodecol = Ext.ComponentMgr.get("facdimcodecol_weidu" + i).getValue();
            o.facdimvalue = Ext.ComponentMgr.get("facdimvalue_weidu" + i).getValue();
            o.facdimfield = Ext.ComponentMgr.get("facdimfield_weidu" + i).getValue();
            if (o.facdimvalue == "") {
                o.facdimvalue = "99999";
                hideCol.push(o.facdimfield);
            }
            array.push(o);
        }
        if (hideCol.length == dimLen) {
            Ext.MessageBox.alert("错误", "请筛选维度后再导出线下采集模板！");
            return;
        }
        var openUrl = basePath
                + '/servlet/ExportServlet?iswcz=false&';
        openUrl += 'repid=' + repid + '&corpid=' + corpid + '&getDemlist=' + getExportDemlist() + "&shuju=1";
        window.open(openUrl);
    }


    //设置列隐藏
    function hideColumn(hiddenCols) {
        var columnModel = grid.getColumnModel();
        for (var i = 0; i < columnModel.getColumnCount(); i++) {
            var dataIndex = columnModel.getDataIndex(i);
            var flag = false;
            for (var j = 0; j < hiddenCols.length; j++) {
                if (dataIndex.indexOf(hiddenCols[j]) >= 0) {
                    flag = true;
                    break;
                }
            }
            //如果需要隐藏的列
            if (flag) {
                columnModel.setHidden(i, true);
            } else {
                var header = columnModel.getColumnHeader(i);
                if (header.indexOf("ID") >= 0) {
                    columnModel.setHidden(i, true);
                } else {
                    columnModel.setHidden(i, false);
                }
            }
        }
    }

    //查询
    function query() {
        store.commitChanges();
    }

    //判断字符串不能以数字开头
    function isDigitzh(s)
    {
        var patrn = /^[0-9-.]{0,32}$/;
        if (patrn.exec(s)) {
            return false;
        } else {
            return true;
        }
    }
    //导入excel
    function importXls(url) {
        var openUrl = basePath
                + 'JarpListener?className=cn.com.jsepc.rep.report.ImportXls';
        openUrl += '&methodName=UserOperate&paramCount=3&param_0=' + url + '&param_1=' + repid + '&param_2=' + roleid;
        httpR_itemInfo = getXMLHttpRequest();
        httpR_itemInfo.onreadystatechange = resultXls;
        httpR_itemInfo.open("POST", openUrl, true);
        httpR_itemInfo.send();
    }

    function resultXls() {
        if (httpR_itemInfo.readyState == 4) {
            if (httpR_itemInfo.status == 200) {
                ret = httpR_itemInfo.responseText;
                alert(ret);
                store.reload();
            }
        }
    }
});